import { Component, OnInit } from '@angular/core';

import { ActivatedRoute } from '@angular/router'
import { getExamById, getQuestionById, insertAnswer } from '../api/api-all';
import { AlertController } from '@ionic/angular';
import { getUserId } from '../api/request';

@Component({
  selector: 'app-page-exam',
  templateUrl: './page-exam.component.html',
  styleUrls: ['./page-exam.component.scss']
})
export class PageExamComponent implements OnInit {

  examData: any = {}

  questionData: any = []

  answerList: Array<any> = []


  constructor(private route: ActivatedRoute, private alertController: AlertController) { }

  async ngOnInit() {
    this.route.queryParams.subscribe(params => {
      const examId = params['examId']

      // 获取试卷
      getExamById(examId).then(res => {
        console.log(res)
        this.examData = res

        // 获取题目
        const questionIds: Array<string> = res.question
        questionIds.forEach(id => {
          getQuestionById(id).then(res => {
            this.questionData.push(res)
          })
        })

      })
    })
  }

  // 添加答案
  addAnswer(questionId: string, answerIndex: number) {
    let list: Array<any> = this.answerList
    const findIndex: number = list.findIndex(obj => obj.questionId === questionId)
    if (findIndex >= 0) {
      list[findIndex] = { questionId: questionId, answerIndex: [answerIndex] }
    } else {
      list.push({ questionId: questionId, answerIndex: [answerIndex] })
    }
  }

  // 提交试卷
  async submitExam() {
    console.log("answerList", this.answerList)
    console.log("questionData", this.questionData)
    const userAnswer: Array<any> = this.answerList
    const questionData: Array<any> = this.questionData
    const userId: any = getUserId()

    // valid
    if (questionData.length !== userAnswer.length) {
      const alert = await this.alertController.create({
        message: '您还有题目未完成',
        buttons: ['OK'],
      })
      await alert.present()
      return;
    }

    // 总分统计
    let scoreSum: number = 0

    // 保存到 answer 中
    for (let ans of userAnswer) {
      const qId: string = ans.questionId
      const questionEntity: any = questionData.find(obj => obj.objectId === qId)

      // 判断对错
      let doRight: boolean
      switch (questionEntity.type) {
        case 0: // 单选
          doRight = questionEntity.answer[0] === ans.answerIndex[0]
          break;
        default:
          doRight = false
      }

      if (doRight) {
        scoreSum += questionEntity.score
      }

      insertAnswer({
        userId: userId,
        answer: ans.answerIndex,
        questionId: qId,
        score: doRight ? questionEntity.score : 0,
        doRight: doRight,
        title: questionEntity.title
      })

    }

    // 统计总分 & 回显
    const alert = await this.alertController.create({
      header: "答题已完成",
      message: '您的分数为：' + scoreSum,
      buttons: [{
        text: '我已知曉',
        handler: () => {
          location.href = "/starnight-student/dashboard"
        }
      }],
    })
    await alert.present()

  }

}
